package com.zhihu.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.zhihu.Enums.LikedStatusEnum;
import com.zhihu.client.AnswerClients;
import com.zhihu.client.QuestionClients;
import com.zhihu.dao.LikeOpusRepository;
import com.zhihu.dao.LikeRepository;
import com.zhihu.pojo.Answer;
import com.zhihu.pojo.LikeOpus;
import com.zhihu.pojo.LikedOpusCount;
import com.zhihu.pojo.Question;
import com.zhihu.pojo.baseVo.BaseResult;
import com.zhihu.pojo.req.QuestionReq;
import com.zhihu.service.LikedOpusService;
import com.zhihu.service.RedisService;
import com.zhihu.utils.RedisKeyUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class LikedServiceImpl implements LikedOpusService {

    @Autowired
    LikeRepository likeRepository;

    @Autowired
    RedisService redisService;

    @Autowired
    QuestionClients questionClients;

    @Autowired
    AnswerClients answerClients;

    @Autowired
    LikeOpusRepository likeOpusRepository;

    //保存点赞信息
    @Override

    public LikeOpus save(LikeOpus likeOpus) {
        return likeRepository.save(likeOpus);
    }

    //批量保存或修改点赞信息
    @Override
    public List<LikeOpus> saveAll(List<LikeOpus> list) {
        return likeRepository.saveAll(list);
    }

    //根据被点赞人的id查询点赞列表（即查询都谁给这个人点赞过）
    @Override
    public List<LikeOpus> getLikedListByLikedUserId(String likedUserId) {
        return likeRepository.findByLikedUserIdAndLikeStatus(likedUserId, LikedStatusEnum.LIKE.getCode());
    }

    //根据点赞人的id查询点赞列表（即查询这个人都给谁点赞过）
    @Override
    public List<LikeOpus> getLikedListByLikedPostId(String likedPostId) {
        return likeRepository.findByLikedPostIdAndLikeStatus(likedPostId, LikedStatusEnum.LIKE.getCode());
    }

    //通过被点赞人和点赞人id和作品Id和作品类型 查询是否存在点赞记录
    @Override
    public LikeOpus getByLikedUserIdAndLikedPostId(String likedUserId, String likedPostId,String followOpusId,String followOpusTap) {
        return likeRepository.getByLikedUserIdAndLikedPostIdAndFollowOpusIdAndFollowOpusTap(likedUserId, likedPostId,followOpusId,followOpusTap);
    }

    //将Redis里的点赞数据存入数据库中
    @Override
    public void transLikedFromRedis2DB() {
        List<LikeOpus> list = redisService.getLikedOpusDataFromRedis();
        System.out.println(list);
        for (LikeOpus like : list) {
            LikeOpus likeOpus = getByLikedUserIdAndLikedPostId(like.getLikedUserId(), like.getLikedPostId(),like.getFollowOpusId(),like.getFollowOpusTap());
            System.out.println(likeOpus);
            if (likeOpus == null) {
                //没有记录，直接存入
                this.save(like);
            } else {
                //有记录，需要更新
                likeOpus.setLikeStatus(like.getLikeStatus());
                this.save(likeOpus);
            }
        }
    }

    //将Redis中的点赞数量数据存入数据库
    @Override
    public void transLikedCountFromRedis2DB() {
        List<LikedOpusCount> list = redisService.getLikedOpusCountFromRedis();
        System.out.println(list);
        for (LikedOpusCount likedOpusCount : list) {
            //更新问题
            if (likedOpusCount.getFollowOpusTap().equals("1")){
                BaseResult baseResult = questionClients.findQuestionById(Integer.valueOf(likedOpusCount.getFollowOpusId()));
                if (baseResult.getCode()==0) {
                    System.out.println(baseResult.getMsg());
                    String s = JSONObject.toJSONString(baseResult.getData());
                    QuestionReq questionReq = JSONObject.parseObject(s, QuestionReq.class);

                    System.out.println(questionReq);
                    if (questionReq!=null){
                        Question question = new Question();
                        //将redis中该问题的点赞总数 封装到questionReq的quesLikeNum字段中
                        Integer likeNum = likedOpusCount.getCount();
                        questionReq.setQuesLikeNum(likeNum);
                        //将接收的questionReq实体转换为question
                        BeanUtils.copyProperties(questionReq,question);
                        //更新点赞数量到数据库中
                        questionClients.updateQuestion(question);
                    }
                }else {
                    System.out.println(baseResult.getMsg());
                }

            }
            //更新回答
            if (likedOpusCount.getFollowOpusTap().equals("2")){
                BaseResult baseResult = answerClients.findAnswerById(Integer.valueOf(likedOpusCount.getFollowOpusId()));
                if (baseResult.getCode()==0) {
                    System.out.println(baseResult.getMsg());
                    String s = JSONObject.toJSONString(baseResult.getData());
                    Answer answer = JSONObject.parseObject(s, Answer.class);
                    if (answer!=null){
                        //将redis中该回答的点赞总数 封装到answer1的ansLikenum字段中
                        Integer likeNum = likedOpusCount.getCount();
                        answer.setAnsLikenum(likeNum);
                        //更新点赞数量到数据库中
                        answerClients.updateAnswer(answer);
                    }
                }else {
                    System.out.println(baseResult.getMsg());
                }
            }

        }
    }

    /**
     * 查询所有的当前用户点赞过的回答
     * @param userId
     * @return
     */

    @Override
    public List getUserLikeData(Integer userId) {
        List<LikeOpus> LikeOpuslist = likeOpusRepository.findByLikedPostIdAndFollowOpusTapAndLikeStatus(userId.toString(), "2", 1);
        List showLikeIds = new ArrayList();
        for (LikeOpus likeOpus:LikeOpuslist){
            showLikeIds.add(Integer.valueOf(likeOpus.getFollowOpusId()));
        }
        System.out.println(showLikeIds);
        return showLikeIds;
    }

}
